import numpy as np
import time
import cv2

# 设定红色阈值，HSV空间
redLower = np.array([170, 100, 100])
redUpper = np.array([179, 255, 255])
# #######识别蓝色
# redLower = np.array([96, 109, 65])
# redUpper = np.array([255, 237, 196])

# 打开摄像头
camera = cv2.VideoCapture(0)
# 等待两秒
time.sleep(3)

# 遍历每一帧
while True:
    # 读取帧
    (ret, frame) = camera.read()

    # 判断是否成功打开摄像头
    if not ret:
        print
        'No Camera'
        break
###########################识别算法#########################################
    # 转到HSV空间
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    # 根据阈值构建掩膜
    mask = cv2.inRange(hsv, redLower, redUpper)
    # 腐蚀操作
    mask = cv2.erode(mask, None, iterations=2)
    # 膨胀操作，其实先腐蚀再膨胀的效果是开运算，去除噪点
    mask = cv2.dilate(mask, None, iterations=2)
    # 检测轮廓
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    if len(cnts) > 0:
        c = max(cnts, key=cv2.contourArea)
        # 确定面积最大的轮廓的外接圆
        ((x, y), radius) = cv2.minEnclosingCircle(c)

##############################################################################

        print("x=", x, "y=", y, "r=", radius)
        # 执行画图
        cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
    cv2.imshow('Frame', frame)

    # 键盘检测，检测到esc键退出
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

# 摄像头释放
camera.release()
# 销毁所有窗口
cv2.destroyAllWindows()
